package org.kfish.framework.helper;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.kfish.framework.annotation.Action;
import org.kfish.framework.bean.Handler;
import org.kfish.framework.bean.Request;
import org.kfish.framework.log.Log;
import org.kfish.framework.log.Log.LogType;
import org.kfish.framework.util.ArrayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LoggerFactoryBinder;


/**
 * Controller helper
 * @author CK
 *
 */
		
public class ControllerHelper {
	
	
	/**
	 * 用于存放 request 和  handler 的 映射关系
	 */
	private static final Map<Request,Handler> ACTION_MAP = new HashMap<>();
	
	static {
	
		//获取所有的controller 类
		Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
		//遍历controllerClassSet
		for(Class<?> controllerClass:controllerClassSet){
			//获取类的所有方法
			Method[] methods = controllerClass.getMethods();
			//遍历 methods
			for(Method method:methods){
				//如果方法上有 @Action注解
				if(method.isAnnotationPresent(Action.class)){
					//从Action 注解中获取URL mapping规则( 即获取@Action(value)中的value )
					Action action = method.getAnnotation(Action.class);
					String mapping = action.value();
					
					//验证 URL mapping 规则
					if(mapping.matches("(\\w+):((/\\w+)*)")){
						String[] array = mapping.split(":");
						if(ArrayUtil.isNotEmpty(array) && array.length ==2){
							//get request method and path
							String requestMethod = array[0];
							String requestPath = array[1];
							Log.getLogger(LogType.SIMPLE).info("check controller - [{}:{}]",requestMethod,requestPath);
							//ready to put to ACTION_MAP
							Request request = new Request(requestMethod, requestPath);
							Handler handler = new Handler(controllerClass, method);
							ACTION_MAP.put(request, handler);
							
						}
					}
					
				}
				
			}	
		}
	}

	/**
	 * 获取 Handler
	 * @param requestMethod
	 * @param requestPath
	 * @return
	 */
	public static Handler getHandler(String requestMethod,String requestPath){
		Request request = new Request(requestMethod, requestPath);
		return ACTION_MAP.get(request);
	}
	
	
}
